package servlet;

import model.Page;
import service.GoodsService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "goods_search", value = "/goods_search")
public class GoodsSearchServlet extends HttpServlet {
    private GoodsService gService = new GoodsService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        int pageNumber = 1;
        if(request.getParameter("pageNumber") != null) {
            try {
                pageNumber=Integer.parseInt(request.getParameter("pageNumber") ) ;
            } catch (Exception e) {
            }
        }
        if(pageNumber<=0) {
            pageNumber=1;
        }
        //搜索商品并分页
        Page p =gService.getSearchGoodsPage(keyword,pageNumber);

        if(p.getTotalPage()==0) {
            p.setTotalPage(1);
            p.setPageNumber(1);
        } else {
            if(pageNumber>=p.getTotalPage()+1) {
                p =gService.getSearchGoodsPage(keyword,pageNumber);
            }
        }
        request.setAttribute("p", p);
        request.setAttribute("keyword", URLEncoder.encode(keyword,"utf-8"));
        request.getRequestDispatcher("/goods_search.jsp").forward(request, response);
    }
}
